import {reqCellPhoneByCode, reqCellPhoneByPassword,reqDetail,reqLogout,reqCellEmailByPassword} from '@/api'
import {setCookie,getCookie,removeCookie} from '@/utils/cookie'
import {setIsLogin,getIsLogin,removeIsLogin} from '@/utils/isLogin'
import { setUserId,getUserId,removeUserId } from '@/utils/userId'
import { setUserInfo,getUserInfo,removeUserInfo } from '@/utils/userInfo'
import {removeUserSonglist} from "@/utils/userSonglist";
const state={
    code:0,
    // 是否登录
    isLogin: getIsLogin(),
    cookie:getCookie(),
    userId:getUserId(),
    userInfo:{},
}
const mutations={
    /* 更新登录状态 */
    UPDATEISLOGIN(state, payload) {
        setIsLogin(payload)
        state.isLogin = payload;
    },
    UPDATETOKEN(state,cookie){
        setCookie(cookie);
        state.cookie = cookie;
    },
    UPDATEUSERINFO(state,userId){
        setUserId(userId);
        state.userId = userId;
    },
    GETUSERINFO(state,userInfo){
        setUserInfo(JSON.stringify(userInfo))
        state.userInfo = userInfo;
    },
    EXIT(state){
        state.userInfo = {};
        state.userId = "";
        state.token = "";
        state.isLogin = false;
        setIsLogin(false)
        removeCookie();
        removeUserSonglist();
        removeUserId();
        removeUserInfo()
    }
}
const actions={
    /* 更新登录状态 */
    updateLogin({ commit }, payload) {
        setIsLogin(payload)
        this.isLogin = payload;
        commit("UPDATEISLOGIN", payload);
    },
    //密码更新Token
    async updateTokenWithEmail({commit},{email,password}){
        try {
            let obj = await reqCellEmailByPassword(email,password);
            if(obj.result.code == 0 && obj.success){
                commit('UPDATETOKEN',obj.result.cookie);
                commit('UPDATEUSERINFO',obj.result.account.id);
                this.$notify({
                    message: "登陆成功",
                    type: "success",
                });
            }
        } catch (error) {
            alert(error);
        }

    },
    //获取用户信息
    async getUserInfo({commit},id){
        let obj = await reqDetail(id);
        commit('GETUSERINFO',obj.result);
    },
    //退出登录
    async exit({commit}){
        await reqLogout();
        commit('EXIT');
    }
}
const getters={

}

export default{
    state,
    mutations,
    actions,
    getters
}